package org.kjtc.controller;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.kjtc.entity.AbnormalRule;
import org.kjtc.entity.BatteryType;
import org.kjtc.entity.BranchCompany;
import org.kjtc.entity.CarInfo;
import org.kjtc.entity.CarTeam;
import org.kjtc.entity.ChargingStation;
import org.kjtc.entity.DeviceObject;
import org.kjtc.entity.Equipment;
import org.kjtc.entity.EquipmentPowerType;
import org.kjtc.entity.EquipmentType;
import org.kjtc.entity.LineInfo;
import org.kjtc.entity.Menu;
import org.kjtc.entity.Page;
import org.kjtc.entity.Role;
import org.kjtc.entity.SubBranchCompany;
import org.kjtc.entity.User;
import org.kjtc.service.AbnormalRuleService;
import org.kjtc.service.BatteryTypeService;
import org.kjtc.service.BranchCompanyService;
import org.kjtc.service.CarInfoService;
import org.kjtc.service.CarTeamService;
import org.kjtc.service.ChargingStationService;
import org.kjtc.service.EquipmentService;
import org.kjtc.service.LineService;
import org.kjtc.service.MenuService;
import org.kjtc.service.RoleService;
import org.kjtc.service.SQLService;
import org.kjtc.service.SubBranchCompanyService;
import org.kjtc.service.UserInfoService;
import org.kjtc.util.Const;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ListController extends BaseController {

	@Resource(name = "equipmentService")
	private EquipmentService equipmentService;

	@Resource(name = "carInfoService")
	private CarInfoService carInfoService;

	@Resource(name = "batteryTypeService")
	private BatteryTypeService batteryTypeService;

	@Resource(name = "roleService")
	private RoleService roleService;

	@Resource(name = "userInfoService")
	private UserInfoService userInfoService;

	@Resource(name = "carTeamService")
	private CarTeamService carTeamService;

	@Resource(name = "lineService")
	private LineService lineService;

	@Resource(name = "menuService")
	private MenuService menuService;

	@Resource(name = "branchCompanyService")
	private BranchCompanyService branchCompanyService;

	@Resource(name = "chargingStationService")
	private ChargingStationService chargingStationService;

	@Resource(name = "subBranchCompanyService")
	private SubBranchCompanyService subBranchCompanyService;

	@Resource(name = "abnormalRuleService")
	private AbnormalRuleService abnormalRuleService;

	@Resource(name = "deviceObject")
    private DeviceObject deviceObject;

	@Resource(name = "sqlService")
	private SQLService sqlService;

	@RequestMapping(value = "branchCompany")
	@ResponseBody
	public List<BranchCompany> getBranchCompany(){
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-运营司查询开始");
		List<BranchCompany> list = null;
		BranchCompany branchCompany = new BranchCompany();
		branchCompany.setBranchCompanyID(this.getBranchCompanyID());
		try {
			list = branchCompanyService.getBranchCompany(branchCompany);
		} catch (Exception e) {
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-运营查询异常:" + e.getMessage());
			return null;
		}
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-运营查询结束");
        return list;
	}
    /**
     * 设备类型
     * @return List
     * */
	@RequestMapping(value = "equipmentType")
	@ResponseBody
    public List<EquipmentPowerType> getPowerType(){

		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-设备类型查询开始");
		List<EquipmentPowerType> list = null;
        try {
        	list = equipmentService.getEquipmentPowerType(null);
        } catch(Exception e){
        	logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-设备类型查询异常:" + e.getMessage());
        	return null;
        }

        logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-设备类型查询结束");
        return list;
    }

	 /**
     * 设备信息
     * @return List
     * */
	@RequestMapping(value = "equipmentNo")
	@ResponseBody
    public List<Equipment> getEquipmentNo(String chargingStationID){

		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电桩信息查询开始");
		List<Equipment> list = null;
		Equipment equipment = new Equipment();
		equipment.setChargingStationID(chargingStationID);
        try {
        	list = equipmentService.getEquipment(equipment);
        } catch(Exception e){
        	logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电桩信息查询异常:" + e.getMessage());
        	return null;
        }

        logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电桩信息查询结束");
        return list;
    }

	 /**
     * 协议类型
     * @return List
     * */
	@RequestMapping(value = "protocolType")
	@ResponseBody
    public List<EquipmentType> getProtocolType(){

		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-协议类型查询开始");
		List<EquipmentType> list = null;
        try {
        	list = equipmentService.getEquipmentType(null);
        } catch(Exception e){
        	logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-协议类型查询异常:" + e.getMessage());
        	return null;
        }

        logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-协议类型查询结束");
        return list;
    }

	/**
     * 车队
     * @return List
     * */
	@RequestMapping(value = "carTeam")
	@ResponseBody
	public List<CarTeam> car(String subBranchCompanyID){

		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-车队查询开始");
		List<CarTeam> list = null;
		CarTeam carTeam = new CarTeam();
	    try {
	    	carTeam.setSubBranchCompanyID(subBranchCompanyID);
	    	list = carTeamService.getCarTeam(carTeam);
	    } catch(Exception e){
	    	logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-车队查询异常:" + e.getMessage());
	    	return null;
	    }

	    logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-车队查询结束");
	    return list;
	}

	/**
     * 车牌号
     * @return List
     * */
	@RequestMapping(value = "carVIN")
	@ResponseBody
	public List<CarInfo> carVIN(){

		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-车牌号查询开始");
		List<CarInfo> list = null;
		CarInfo carInfo = new CarInfo();
		carInfo.setBranchCompanyID(this.getBranchCompanyID());
	    try {
	    	list = carInfoService.getCarInfo(carInfo);
	    } catch(Exception e){
	    	logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-车牌号查询异常:" + e.getMessage());
	    	return null;
	    }

	    logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-车牌号查询结束");
	    return list;
	}

	@RequestMapping(value = "batteryType")
	@ResponseBody
    public List<BatteryType> getBatteryType(){

		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-电池类型查询开始");
		List<BatteryType> list = null;
        try {
        	list = batteryTypeService.getBatteryType(null);
        } catch(Exception e){
        	logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-电池类型查询异常:" + e.getMessage());
        	return null;
        }

        logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-电池类型查询结束");
        return list;
    }

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "role")
	@ResponseBody
	public List<Role> getRole(){
	  logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-角色查询开始");
	  List<Role> roleList = null;
	  Role role = new Role();
	  User user = this.getUesr();
	  if (user.getAuthorities().iterator() != null) {
		 role.setRoleID(user.getAuthorities().iterator().next().toString());
	  }
	  try {
		 roleList = (List<Role>)this.getSessionAttribute(Const.SESSION_ROLENAME);
		 if (roleList == null) {
			 roleList = roleService.getRolesInfo(role);
			 this.setSessionAttribute(Const.SESSION_ROLENAME, roleList);
		 }
	  } catch (Exception e) {
		 logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-角色查询异常:" + e.getMessage());
		 return null;
	  }
	  logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-角色查询结束");
	   return roleList;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "menuName")
	@ResponseBody
	public List<Menu> getMenuName(){
	  logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-菜单名称查询开始");
	  List<Menu> menuList = null;
	  try {
		  menuList = (List<Menu>)this.getSessionAttribute(Const.SESSION_MENUNAME);
		 if (menuList == null) {
			 menuList = menuService.geMenuName(null);
			 this.setSessionAttribute(Const.SESSION_MENUNAME, menuList);
		 }
	  } catch (Exception e) {
		 logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-菜单名称查询异常:" + e.getMessage());
		 return null;
	  }
	  logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-菜单名称查询结束");
	   return menuList;
	}

	/**
     * 线路名称
     * @return List
     * */
	@RequestMapping(value = "lineName")
	@ResponseBody
	public List<LineInfo> line(String teamID, String subBranchCompanyID){

		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-线路名称查询开始");
		List<LineInfo> list = null;
		LineInfo lineInfo = new LineInfo();
		lineInfo.setTeamID(teamID);
		lineInfo.setSubBranchCompanyID(subBranchCompanyID);
	    try {
	    	list = lineService.getLineInfo(lineInfo);
	    } catch(Exception e){
	    	logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-线路名称查询异常:" + e.getMessage());
	    	return null;
	    }

	    logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-线路名称查询结束");
	    return list;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "chargingStation")
	@ResponseBody
	public List<ChargingStation> getchargingStation(ChargingStation chargingStation){

		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站名称列表查询开始");
		List<ChargingStation> chargingStationList = null;
		chargingStation.setBranchCompanyID(this.getBranchCompanyID());
		try {
			chargingStationList = (List<ChargingStation>)this.getSessionAttribute(Const.SESSION_CHARGINGSTATIONNAME);
			if (chargingStationList == null) {
				chargingStationList = chargingStationService.getChargingStationName(chargingStation);
				this.setSessionAttribute(Const.SESSION_CHARGINGSTATIONNAME, chargingStationList);
			}
			if (chargingStation.getBulidStatus() != null && !chargingStation.getBulidStatus().isEmpty()) {
				List<ChargingStation> chargingStationList3 = new ArrayList<ChargingStation>();
				for (ChargingStation chargingStation3 : chargingStationList) {
					if (chargingStation.getBulidStatus().equals(chargingStation3.getBulidStatus())) {
						chargingStationList3.add(chargingStation3);
					}
				}
				chargingStationList = chargingStationList3;
			}
		} catch (Exception e) {
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站名称列表查询异常:" + e.getMessage());
			return null;
		}
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站名称列表查询结束");
		return chargingStationList;
	}

	 /**
     * 分公司信息
     * @return List
     * */
	@RequestMapping(value = "subBranchCompany")
	@ResponseBody
    public List<SubBranchCompany> getSubBranchCompany(String branchCompanyID){

		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "分公司列表查询开始");
		List<SubBranchCompany> list = null;
		SubBranchCompany subBranchCompany = new SubBranchCompany();
		subBranchCompany.setBranchCompanyID(branchCompanyID);
        try {
        	list = subBranchCompanyService.getSubBranchCompany(subBranchCompany);
        } catch(Exception e){
        	logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "分公司列表查询异常:" + e.getMessage());
        	return null;
        }

        logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "分公司列表查询结束");
        return list;
    }

	@RequestMapping(value = "abnormalLevel")
	@ResponseBody
    public List<AbnormalRule> getAbnormalLevel(){

		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-异常等级查询开始");
		List<AbnormalRule> list = null;
        try {
        	list = abnormalRuleService.getAbnormalLevel(null);
        } catch(Exception e){
        	logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-异常等级查询异常:" + e.getMessage());
        	return null;
        }

        logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "下拉列表-异常等级查询结束");
        return list;
    }

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "memoryCache")
	@ResponseBody
    public Object getMemoryCache(String memoryCacheType, String memoryCacheContent){

		Map<String, Object> map = new HashMap<String, Object>();
		if (memoryCacheType == null || memoryCacheType.isEmpty()) {
			map.put("result", "MemoryCacheTypeEmpty");
		}
		String message = "";
		if (memoryCacheContent == null || memoryCacheContent.isEmpty()) {
			message = "所有缓存" + memoryCacheType;
		} else {
			message = "缓存" + memoryCacheType + "【" + memoryCacheContent + "】";
		}
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "查询" + message);


		if ("SESSION".equals(memoryCacheType)) {
			if (memoryCacheContent != null && !memoryCacheContent.isEmpty()) {
				map.put("memoryCache", this.getSession().getAttribute(memoryCacheContent));
			} else {
				Enumeration enumeration= this.getSession().getAttributeNames();
				List<String> sessionList = new ArrayList<String>();
				while(enumeration.hasMoreElements()){
					sessionList.add(enumeration.nextElement().toString());
				}
				map.put("memoryCache", sessionList);
			}
		} else if ("MAP".equals(memoryCacheType)) {
			Class cls = DeviceObject.class;
            Method[] methods = cls.getMethods();
            List<String> mapList = new ArrayList<String>();
            if (memoryCacheContent != null && !memoryCacheContent.isEmpty()) {
            	try {
            		for (Method method : methods) {
            			if (method.getName().indexOf(memoryCacheContent) >= 0) {
							Method getMethod = cls.getMethod(method.getName());
							map.put("memoryCache", getMethod.invoke(deviceObject));
							break;
            			}
                    }
				} catch (Exception e) {
					map.put("result", "Error");
					e.printStackTrace();
					return map;
				}
            } else {
            	for (Method method : methods) {
            		if (method.getName().toLowerCase().indexOf("get") >= 0 && method.getName().toLowerCase().indexOf("map") >= 0) {
            			mapList.add(method.getName());
            		}
                }
            	map.put("memoryCache", mapList);
            }
		}
		map.put("result", "Success");

        return map;
    }


	@RequestMapping(value = "sql")
	@ResponseBody
    public Object searchData(String sql, String page, String rows){

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "直通使用sql语句查询数据库" + sql);

		if (page == null || page.isEmpty()) {
			page = "1";
		}
		if (rows == null || rows.isEmpty()) {
			rows = "10";
		}
		Page pageQuery = getPage();
		pageQuery.setCurrentPage(Integer.parseInt(page));
		pageQuery.setCurrentResult((Integer.parseInt(page) - 1) * (Integer.parseInt(rows)));
		pageQuery.setShowCount(Integer.parseInt(rows));

		if (sql == null || sql.isEmpty()) {
			map.put("result", "SQLEmpty");
		} else {
			List<Object> list = null;
			try {
				list = sqlService.searchSQLPage(sql, pageQuery);
				map.put("result", "Success");
				map.put("dataList", list);
				map.put("totalCnt", pageQuery.getTotalResult());
				map.put("totalPage", pageQuery.getTotalPage());
			} catch(Exception e){
				map.put("result", "Error");
				logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "直通使用sql语句查询数据库异常:" + e.getMessage());
			}
		}

        return map;
    }
}